package com.merak.rebot.utils;


import com.ctg.behavior.utils.CtDateUtils;
import lombok.extern.slf4j.Slf4j;

import java.io.*;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Slf4j
public class FileUtil {
	
	public static List<String> loadSqlsFromFile(String filename) throws IOException {
		List<String> sqls = new ArrayList<String>();
		InputStream is = FileUtil.class.getResourceAsStream(filename);
		if (is != null) {
			BufferedReader reader = null;
			try {
				reader = new BufferedReader(new InputStreamReader(is));
				StringBuilder sql = new StringBuilder();
				String line = reader.readLine();
				while (line != null) {
					if (!line.trim().equals("")) {
						sql.append(" ");
						sql.append(line);
						sql.append("\n");
						if (line.indexOf(";") > -1) {
							sql.deleteCharAt(sql.indexOf(";"));
							sqls.add(sql.toString());
							sql.delete(0, sql.length() - 1);
						}
					}
					line = reader.readLine();
				}
			} finally {
				if (reader != null) {
					try {
						reader.close();
					} catch (IOException e) {
					}
				}
			}
		} else {
			log.warn("the file " + filename + " is not located!");
		}

		return sqls;
	}
	
	/**
	 * List file names in the given path
	 * @param dirPathName
	 * @param filenamePattern
	 * @return
	 * @throws Exception
	 */
	public static final String[] listFileNames(final String dirPathName, final String filenamePattern)
			throws Exception {
		if (dirPathName == null) {
			throw new Exception("The given path is null");
		}

		File dir = new File(dirPathName);
		if (!dir.isDirectory()) {
			throw new Exception("The given file path is not a directory: " + dirPathName);
		}

		FilenameFilter filter = new FilenameFilter() {
			@Override
			public boolean accept(File dir, String name) {
				return name.matches(filenamePattern);
			}
		};

		return dir.list(filter);
	}

	/**
	 * List files in the given path
	 * @param dirPathName
	 * @param filenamePattern
	 * @return
	 * @throws Exception
	 */
	public static final File[] listFiles(final String dirPathName, final String filenamePattern) throws Exception {
		if (dirPathName == null) {
			throw new Exception("The given path is null");
		}

		File dir = new File(dirPathName);
		if (!dir.isDirectory()) {
			throw new Exception("The given file path is not a directory: " + dirPathName);
		}

		FilenameFilter filter = new FilenameFilter() {
			@Override
			public boolean accept(File dir, String name) {
				return name.matches(filenamePattern);
			}
		};

		return dir.listFiles(filter);
	}

	public static void moveFileNew(final String sourceFilePath, final String targetFilePath,
			final String sourceFilename) throws Exception {
		String srcFileName = sourceFilePath + File.separator + sourceFilename;
		String dstFileName = targetFilePath + File.separator + sourceFilename;
		moveAFileNew(srcFileName, dstFileName);
	}

	// 解码完成后,移动文件到备份目录,并且去掉SR后缀
	public static void moveFileNewDelSR(final String sourceFilePath, final String targetFilePath,
			final String sourceFilename, final String dstName) throws Exception {
		String srcFileName = sourceFilePath  + sourceFilename;
		String dstFileName = targetFilePath + dstName;
		moveAFileNew(srcFileName, dstFileName);
	}

	public static void moveFileErr(final String sourceFilePath, final String targetFilePath,
			final String sourceFilename) throws Exception {
		String srcFileName = sourceFilePath + File.separator + sourceFilename;
		String dstFileName = targetFilePath + File.separator + "F2000" + sourceFilename;
		moveAFileNew(srcFileName, dstFileName);
	}

	public static void moveAFileNew(String src, String dst) throws Exception {
		File src_file_ = new File(src);
		File dst_file_ = new File(dst);
		try {
			if (src_file_.renameTo(dst_file_)) {
				return;
			}

			copyFile(src, dst);

			if (!src_file_.delete()) {
				throw new Exception(String.format("delete (%s) error after copy to (%s)", src, dst));
			}
		} catch (Exception e) {
			throw new Exception(String.format("MoveAFile(%s,%s) exception:%s", src, dst, e.getMessage()));
		}
	}

	/**
	 * Copy file from source file path to target file path and rename the file
	 * 
	 * @param sourceFilePath
	 * @param targetFilePath
	 * @param sourceFilename
	 * @param targetFilename
	 * @throws Exception
	 */
	public static final void copyFile(final String sourceFilePath, final String targetFilePath,
			final String sourceFilename, final String targetFilename) throws Exception {
		File sourceFile = new File(sourceFilePath + File.separator + sourceFilename);
		File targetFile = new File(targetFilePath + File.separator + targetFilename);
		FileInputStream fis = null;
		FileOutputStream fos = null;
		try {
			fis = new FileInputStream(sourceFile);
			fos = new FileOutputStream(targetFile);
			byte[] buf = new byte[1024];
			int i = 0;
			while ((i = fis.read(buf)) != -1) {
				fos.write(buf, 0, i);
			}
			fos.flush();
		} finally {
			if (fis != null) {
				fis.close();
			}
			if (fos != null) {
				fos.close();
			}
		}
	}

	public static final void copyFile(String srcFileName, String destFileName) throws Exception {
		File srcFile = new File(srcFileName);
		File destFile = new File(destFileName);
		copyFile(srcFile, destFile);
	}

	public static final void copyFile(File srcFile, File destFile) throws Exception {
		FileInputStream fis = null;
		FileOutputStream fos = null;
		try {
			fis = new FileInputStream(srcFile);
			fos = new FileOutputStream(destFile);
			byte[] buf = new byte[1024];
			int i = 0;
			while ((i = fis.read(buf)) != -1) {
				fos.write(buf, 0, i);
			}
			fos.flush();
		} finally {
			if (fis != null) {
				fis.close();
			}
			if (fos != null) {
				fos.close();
			}
		}
	}

	/**
	 * Copy file from source file path to target file path
	 * 
	 * @param sourceFilePath
	 * @param targetFilePath
	 * @param sourceFilename
	 * @throws Exception
	 */
	public static final void copyFile(final String sourceFilePath, final String targetFilePath,
			final String sourceFilename) throws Exception {
		copyFile(sourceFilePath, targetFilePath, sourceFilename, sourceFilename);
	}

	/**
	 * Write some lines into a file
	 * 
	 * @param filename
	 * @param lines
	 * @throws IOException
	 */
	public static final void writeFile(final String filename, List<String> lines, boolean append) throws IOException {
//		BufferedWriter writer = null;
		try (BufferedWriter writer = new BufferedWriter(new FileWriter(new File(filename), append))){
			if (lines != null) {
				for (String line : lines) {
					writer.write(line);
					writer.newLine();
				}
				writer.flush();
			}
		}
	}


	public static void createFileDir(String dirPath) {
		File dir = new File(dirPath);
		if (!dir.exists() || !dir.isDirectory()) {
			dir.mkdirs();
			dir.setWritable(true, false);
		}
	}

	public final static String FILE_CHARSET_UTF8 = "UTF-8";

	public static String buildFilePath(String path, String appendPath) {
		char lastChar = path.charAt(path.length() - 1);
		if ('\\' != lastChar || '/' != lastChar) {
			path += File.separator;
		}
		return path + appendPath;
	}

	public static void isDirectory(String bakPath) throws IOException {
		File file = new File(bakPath);
		if(!file.exists()){
			file.mkdirs();
		}
	}

	//如果为空，返回""
	public static String ches (String str){
		if (str==null || "null".equals(str) || "NULL".equals(str)){
			return "";
		}
		//如果字符串中有| 要去掉
		return str.replace("|","");
	}

	public static List<String> readFile(File file) {
		// Construct BufferedReader from FileReader
		List<String> lines = new ArrayList<>();
		try (BufferedReader br = new BufferedReader(new FileReader(file))){
			String line = null;
			while ((line = br.readLine()) != null) {
				lines.add(line);
			}
		}catch (IOException e){
			log.error("读取文件信息失败，文件名{}",file.getName(),e);
		}
		return lines;

	}

	public static String getFileNameNoEx(String filename) {
		if ((filename != null) && (filename.length() > 0)) {
			int dot = filename.lastIndexOf('.');
			if ((dot >-1) && (dot < (filename.length()))) {
				return filename.substring(0, dot);
			}
		}
		return filename;
	}

	public static String getBakFileName(String filename) {
		if ((filename != null) && (filename.length() > 0)) {
			int dot = filename.lastIndexOf('.');
			if ((dot >-1) && (dot < (filename.length()))) {
				String strTime = CtDateUtils.getDateTime14N(new Date());
				return filename.substring(0, dot)+"."+ strTime +filename.substring(dot);
			}
		}
		return filename;
	}


}
